package com.simu.towercrane.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.util.android.view.CCPullLisvtView;
import cc.util.android.view.CCPullLisvtView.CCOnListViewListener;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.cn.adapters.ArticleListAdapter;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.simu.towercrane.R;
import com.simu.towercrane.activity.BusinessActivity;
import com.simu.towercrane.activity.NewsActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class FragmentZhiXun extends BaseFragmentTwo{
	View view=null;
	private Context mContext;
	private int currentWhere;
	private ImageView[] tips;
	private boolean IsTheEnd=false;
	private ViewPager viewPager;
	private ImageView[] mImageViews;
	private ArrayList<String> listImage = new ArrayList<String>();
	private int FITSTSHOWNUM=10;
	private int LOADMORE=10;
	private int[] imgIdArry;
	ArticleListAdapter articleListAdapter;
	private AVQuery<AVObject> query;
	ArrayList<Map<String,Object>> marticleListHashMap;
	private CCPullLisvtView mListView;
	private boolean isLoop=true;
	private Handler handler = new Handler() {  
		  
        @Override  
        public void handleMessage(Message msg) {  
            super.handleMessage(msg);  
            
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1); 
            setImageBackground(viewPager.getCurrentItem() % mImageViews.length);
        }  
        
    };  
	 @Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {
		 mContext=getActivity();
		 if(view==null){
		 		Log.d("fragmentLife", "FragmentTwoonCreateView");
		 		view=inflater.inflate(R.layout.fragment_glasses_zhixun, null);
		 }
		 
		
		 addimage();
	      initnews();
		 Tool.destroyParent(view);
		 return view;		 
	 }
	 
	 
	 
	 public void initnews(){
		 mListView=(CCPullLisvtView)view.findViewById(R.id.news_list);
		 marticleListHashMap=new ArrayList<Map<String,Object>>();
		 articleListAdapter=new ArticleListAdapter(getActivity(), marticleListHashMap, R.layout.list_article_item, 
				new String[]{"image","title","text"} , new int[]{R.id.list_article_image,
			 R.id.list_article_title,R.id.list_article_newsdetals});
		 mListView.setAdapter(articleListAdapter);
		 
		 mListView.setCCOnListViewListener(new CCOnListViewListener() {
			
			@Override
			public void onRefresh(CCPullLisvtView view) {
				// TODO Auto-generated method stub
				IsTheEnd=false;
				query = new AVQuery<AVObject>("Article");
				query.setLimit(FITSTSHOWNUM);
				query.findInBackground(new FindCallback<AVObject>() {
					
					@Override
					public void done(List<AVObject> arg0, AVException arg1) {
						if(arg0!=null)
						{
						currentWhere=arg0.size();
						marticleListHashMap.clear();
						if(arg0.size()<FITSTSHOWNUM)
						{
							IsTheEnd=true;
						}
						// TODO Auto-generated method stub
						for(AVObject article:arg0){
							final Map<String,Object> articleMap=new HashMap<String,Object>();
						
							articleMap.put("title", article.getString("title"));
							articleMap.put("text", article.getString("summary"));
							articleMap.put("ObjectID", article.getObjectId());
							if(article.getAVFile("listImageFile")!=null){
							articleMap.put("image", article.getAVFile("listImageFile").getUrl());
							
							
							}
							marticleListHashMap.add(articleMap);
							articleListAdapter.notifyDataSetChanged();
							mListView.stopRefresh();
						}
					}
					}
				});
			}
			
			@Override
			public void onLoadMore(CCPullLisvtView view) {
				// TODO Auto-generated method stub
				// TODO Auto-generated method stub
				if(!IsTheEnd){
					query = new AVQuery<AVObject>("Article");
					query.skip(currentWhere);
					query.setLimit(LOADMORE);
				
				query.findInBackground(new FindCallback<AVObject>() {
					
					@Override
					public void done(List<AVObject> arg0, AVException arg1) {
						// TODO Auto-generated method stub
						currentWhere+=arg0.size();
						if(arg0.size()<LOADMORE)
						{
							IsTheEnd=true;
						}
						
						for(AVObject article:arg0){
							final Map<String,Object> articleMap=new HashMap<String,Object>();
						
							articleMap.put("title", article.getString("title"));
							articleMap.put("text", article.getString("summary"));
							articleMap.put("ObjectID", article.getObjectId());
							if(article.getAVFile("listImageFile")!=null){
							articleMap.put("image", article.getAVFile("listImageFile").getUrl());
							
							
							}
							marticleListHashMap.add(articleMap);
							articleListAdapter.notifyDataSetChanged();
							mListView.stopLoadMore();
						}
					}
				});
				}
				else{
					mListView.stopLoadMore();
					Toast.makeText(getActivity(), "已经全部加载完", Toast.LENGTH_LONG);
				}
			}
		});
		 setItemClick();
		 
		 
		 
	 }
	 
	 
	 private void setItemClick(){
		 
		 mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				// TODO Auto-generated method stub
				HashMap map=(HashMap) parent.getAdapter().getItem(position);
				String Id=map.get("ObjectID")+"";
				Toast.makeText(getActivity(), Id, 1000).show();
				Intent intent= new Intent();
				intent.putExtra("ObjectID", Id);
				intent.setClass((Activity)getActivity(), NewsActivity.class);
				getActivity().startActivity(intent);
				
			}
		});
		
		 
	 }
	 
	 
	 public void initheadimg(){
		// 自动切换页面功能  
	       
		 ViewGroup group = (ViewGroup)view.findViewById(R.id.news_viewGroup);  
	      viewPager = (ViewPager)view.findViewById(R.id.news_viewPager); 
		 
	     imgIdArry = new int[]{R.drawable.logo_ui,R.drawable.logo_ui,R.drawable.logo_ui}; 
		
	   
			int a= listImage.size();
//	     if(a>0)
//	     {
//	    	 for(int i=0;i<3&&i<a;i++)
//	    		 imgIdArry[i]= ImageLoader.getInstance().loadImageSync(listImage.get(i)+"").describeContents();
//	    	 
//	     }
	     
	     
		 
		 tips = new ImageView[imgIdArry.length];
		 for(int i=0; i<tips.length; i++){  
	            ImageView imageView = new ImageView(mContext);  
	            imageView.setLayoutParams(new LayoutParams(10,10));  
	            tips[i] = imageView;  
	            if(i == 0){  
	                tips[i].setBackgroundResource(R.drawable.page_indicator_focused);  
	            }else{  
	                tips[i].setBackgroundResource(R.drawable.page_indicator_unfocused);  
	            }  
	              
	            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,    
	                    LayoutParams.WRAP_CONTENT));  
	            layoutParams.leftMargin = 5;  
	            layoutParams.rightMargin = 5;  
	            group.addView(imageView, layoutParams);  
	        }  
		 mImageViews = new ImageView[imgIdArry.length];  
	        for(int i=0; i<mImageViews.length; i++){  
	            ImageView imageView = new ImageView(mContext);  
	            mImageViews[i] = imageView;  
//	            imageView.setBackgroundResource(imgIdArry[i]);  
	            ImageLoader.getInstance().displayImage(listImage.get(i) + "",
	            		mImageViews[i]);
	        } 
	        viewPager.setAdapter(new MyAdapter());
	        
	        if(mImageViews!=null)
	        {
	        new Thread(new Runnable() {  
	      	  
	            @Override  
	            public void run() {  
	                  while(isLoop)
	                  {
	                    SystemClock.sleep(4000);  
	                    handler.sendEmptyMessage(0);  
	                  }
	            }  
	        }).start();
	        }
		 
	 }
	 
	 public void addimage(){
		 
		 
		 
		 query = new AVQuery<AVObject>("Article");
			query.findInBackground(new FindCallback<AVObject>() {
				
				@Override
				public void done(List<AVObject> arg0, AVException arg1) {
					if(arg0!=null)
					{
					// TODO Auto-generated method stub
					
				
					for(AVObject article:arg0){
						if(article.getAVFile("listImageFile")!=null){
						String imageUrl =article.getAVFile("listImageFile").getUrl();
						listImage.add(imageUrl);
						
						}
					}
					initheadimg();
					}
				}
			});
	 }
	 
	 public class MyAdapter extends PagerAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			 return Integer.MAX_VALUE; 
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			 return arg0 == arg1; 
		}
		
		
		  @Override  
	        public void destroyItem(View container, int position, Object object) {  
	            ((ViewPager)container).removeView(mImageViews[position % mImageViews.length]);  
	              
	        } 
		  @Override  
	        public Object instantiateItem(View container, int position) {  
	            ((ViewPager)container).addView(mImageViews[position % mImageViews.length], 0);  
	            return mImageViews[position % mImageViews.length];  
	        }  
		 
		 
	 }
	 
	 @Override  
	    public void onPageScrollStateChanged(int arg0) {  
	          
	    }  
	  
	    @Override  
	    public void onPageScrolled(int arg0, float arg1, int arg2) {  
	          
	    }  
	  
	    @Override  
	    public void onPageSelected(int arg0) {  
	        setImageBackground(arg0 % mImageViews.length);  
	    } 
	 
	
	    private void setImageBackground(int selectItems){  
	        for(int i=0; i<tips.length; i++){  
	            if(i == selectItems){  
	                tips[i].setBackgroundResource(R.drawable.page_indicator_focused);  
	            }else{  
	                tips[i].setBackgroundResource(R.drawable.page_indicator_unfocused);  
	            }  
	        }  
	    }
		@Override
		public void onDestroyView() {
			// TODO Auto-generated method stub
			isLoop=false;
			super.onDestroyView();
		}

	 
	 
	 
	 
	 
	 
}
